package com.sptpc.learnspring.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sptpc.learnspring.mapper.DrinkMapper;
import com.sptpc.learnspring.model.Drink;
import com.sptpc.learnspring.service.IDrinkService;
import com.sptpc.learnspring.vo.DrinkVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DrinkServiceImpl implements IDrinkService {
    @Autowired
    private DrinkMapper drinkMapper;

    // 使用PageHelper实现分页
    @Override
    public PageInfo<Drink> getAllDrinks(Integer page, Integer size) {
        PageHelper.startPage(page, size);
        List<Drink> list = drinkMapper.selectAll();
        PageInfo<Drink> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public Drink addNewDrink(Drink drink) {
        int id = drinkMapper.insertSelective(drink);
        if (id>=1) { // 返回值为影响的行数
            return drink; // mybatis插入操作成功会自动回填id到原实体类内
        }
        return null; // 后面通过抛出业务错误进行全局处理
    }

    @Override
    public DrinkVO getDrinkById(Long id) {
        return drinkMapper.selectByPrimaryKeyWithCategory(id);
    }

    @Override
    public List<Drink> searchDrinksByKey(String key) {
        return drinkMapper.selectByName(key);
    }

    @Override
    public Drink updateDrink(Drink updateDrink) {
        drinkMapper.updateByPrimaryKeySelective(updateDrink);
        return drinkMapper.selectByPrimaryKey(updateDrink.getId());
    }
}
